import dayjs from 'dayjs'
import rt from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import store from '@/store'

const dateFilter = (val, format = 'YYYY-MM-DD') => {
  if (typeof val === 'number' && val % 1 === 0) {
    val = parseInt(val)
    return dayjs(val).format(format)
  } else {
    const date = new Date(val)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day
      .toString()
      .padStart(2, '0')}`
    return formattedDate
  }
}

dayjs.extend(rt)

function relativeTime(val) {
  if (!isNaN(val)) {
    val = parseInt(val)
  }
  return dayjs()
    .locale(store.getters.language === 'zh' ? 'zh-cn' : 'en')
    .to(dayjs(val))
}

const jsonFilter = (val) => {
  if (val === undefined) return ''
  return JSON.parse(val)
}

const discountFilterShow = (val) => {
  if (!isNaN(val)) {
    val = parseInt(val)
  } else {
    val = 1000
  }
  return val / 100 + '折'
}

const discountFilter = (val) => {
  if (!isNaN(val)) {
    val = parseInt(val)
  } else {
    val = 1000
  }
  return val / 100
}

const moneyFilter = (val) => {
  if (!isNaN(val)) {
    val = parseInt(val)
  } else {
    val = 0
  }
  return val / 1000
}

const moneyFilterShow = (val) => {
  if (!isNaN(val)) {
    val = parseInt(val)
  } else {
    val = 0
  }
  return '￥' + (val / 1000).toFixed(2)
}

const payTypeShow = (val) => {
  if (!isNaN(val)) {
    val = parseInt(val)
  } else {
    val = 0
  }

  switch (val) {
    case 0:
      return '现金' // Cash
    case 1:
      return '微信' // WeChat
    case 2:
      return '支付宝' // Alipay
    case 3:
      return '银行卡' // Bank Card
    default:
      return '未知' // Unknown
  }
}

const statusFilter = (val) => {
  console.log(val)
  if (val === 1) {
    return '禁用'
  } else {
    return '启用'
  }
}

const memberFilter = (name) => {
  return `会员【${name}】详情`
}

const rechargeDateFilter = (val, format = 'YYYY-MM-DD HH:mm') => {
  if (typeof val === 'number' && val % 1 === 0) {
    val = parseInt(val)
    return dayjs(val).format(format)
  } else {
    return '暂无'
  }
}

const feeOperateType = (val) => {
  if (typeof val === 'number') {
    val = parseInt(val)
  } else {
    val = 0
  }
  if (val === 0) {
    return '充值'
  } else if (val === 1) {
    return '消费'
  } else {
    return '退款'
  }
}

export default (app) => {
  app.config.globalProperties.$filters = {
    dateFilter,
    jsonFilter,
    relativeTime,
    moneyFilter,
    payTypeShow,
    moneyFilterShow,
    feeOperateType,
    discountFilter,
    memberFilter,
    rechargeDateFilter,
    discountFilterShow,
    statusFilter
  }
}
